<template>
  <div>
    <el-dialog
      append-to-body
      v-model="dialogVisible"
      title="新建用户"
      width="30%"
      center
    >
      <!-- E1. 传递给form，做展示 -->
      <cy-form v-bind="modelConfig" v-model="formData"></cy-form>
      <slot></slot>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="handleConfirmClick">
            Confirm
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import cyForm from '@/base-ui/form'
import { useStore } from 'vuex'
import { defineComponent, ref, watch } from 'vue'

export default defineComponent({
  props: {
    modelConfig: {
      type: Object,
      required: true
    },
    defaultInfo: {
      type: Object,
      default: () => ({})
    },
    pageName: {
      type: String,
      required: true
    },
    otherInfo: {
      type: Object,
      default: () => ({})
    }
  },
  components: {
    cyForm
  },
  setup(props) {
    const dialogVisible = ref(false)
    const formData = ref<any>({})
    //D1. 此处绑定defaultInfo的数据，并且对数据的动态赋值给formData，传递给form做界面展示
    watch(
      () => props.defaultInfo,
      (newValue) => {
        for (const item of props.modelConfig.formItems) {
          formData.value[`${item.field}`] = newValue[`${item.field}`]
        }
      }
    )
    const store = useStore()
    // 点击确定按钮后的逻辑，但是需要区分是edit / create用户的确认按钮
    const handleConfirmClick = () => {
      dialogVisible.value = false
      //编辑
      if (Object.keys(props.defaultInfo).length) {
        store.dispatch('systemModule/editPageDataAction', {
          pageName: props.pageName,
          editData: { ...formData.value, ...props.otherInfo },
          id: props.defaultInfo.id
        })
      } else {
        //新建
        store.dispatch('systemModule/createPageDataAction', {
          pageName: props.pageName,
          newData: { ...formData.value, ...props.otherInfo }
        })
      }
    }
    return {
      dialogVisible,
      formData,
      handleConfirmClick
    }
  }
})
</script>

<style scoped></style>
